import os
import argparse
import re
from pathlib import Path

def modify_gradle_properties(project_dir):
    """修改gradle.properties文件，添加阿里云镜像配置"""
    gradle_props_path = os.path.join(project_dir, 'gradle.properties')

    # 检查文件是否存在，不存在则创建
    if not os.path.exists(gradle_props_path):
        print(f"创建新的gradle.properties文件: {gradle_props_path}")
        with open(gradle_props_path, 'w') as f:
            pass

    # 读取文件内容
    with open(gradle_props_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # 检查是否已存在镜像配置
    has_mirror_config = any('systemProp.http.proxyHost' in line for line in lines)

    if not has_mirror_config:
        # 添加镜像配置
        mirror_config = [
            '# 添加阿里云镜像配置\n',
            'systemProp.http.proxyHost=mirrors.aliyun.com\n',
            'systemProp.http.proxyPort=80\n',
            'systemProp.https.proxyHost=mirrors.aliyun.com\n',
            'systemProp.https.proxyPort=80\n'
        ]

        # 在文件开头插入配置
        lines = mirror_config + lines

        # 保存修改
        with open(gradle_props_path, 'w', encoding='utf-8') as f:
            f.writelines(lines)
        print(f"已更新gradle.properties: {gradle_props_path}")
    else:
        print(f"gradle.properties中已存在镜像配置，跳过修改")

def modify_build_file(file_path):
    """修改build.gradle或build.gradle.kts文件，替换仓库地址为阿里云镜像"""
    if not os.path.exists(file_path):
        print(f"错误: 未找到build文件: {file_path}")
        return

    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # 检查是否已使用阿里云镜像
    if 'maven.aliyun.com' in content:
        print(f"{os.path.basename(file_path)}中已使用阿里云镜像，跳过修改")
        return

    is_kts = file_path.endswith('.kts')

    # 定义要替换的仓库配置和对应的阿里云镜像
    original_repos = {
        'mavenCentral\\(\\)': 'maven { url "https://maven.aliyun.com/repository/central" }',
        'jcenter\\(\\)': 'maven { url "https://maven.aliyun.com/repository/jcenter" }',
        'google\\(\\)': 'maven { url "https://maven.aliyun.com/repository/google" }'
    }

    # 根据文件类型调整语法
    if is_kts:
        for repo, replacement in original_repos.items():
            original_repos[repo] = replacement.replace('{ url ', '("').replace(' }', '")')

    # 替换仓库配置
    for repo_pattern, replacement in original_repos.items():
        content = re.sub(repo_pattern, replacement, content)

    # 添加阿里云Gradle插件仓库
    gradle_plugin_mirror = 'maven { url "https://maven.aliyun.com/repository/gradle-plugin" }'
    if is_kts:
        gradle_plugin_mirror = 'maven(url = "https://maven.aliyun.com/repository/gradle-plugin")'

    if gradle_plugin_mirror not in content:
        # 查找repositories块
        repo_pattern = r'repositories\s*\{|\s*repositories\s*\{|\s*repositories\s*\(\s*\)\s*\{|\s*repositories\s*\{\s*'
        match = re.search(repo_pattern, content)

        if match:
            # 在repositories块的开始位置添加阿里云Gradle插件仓库
            repo_block_start = match.end()
            content = content[:repo_block_start] + '\n        ' + gradle_plugin_mirror + content[repo_block_start:]

    # 保存修改
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    print(f"已更新{os.path.basename(file_path)}: {file_path}")

def main():
    parser = argparse.ArgumentParser(description='配置Gradle项目使用阿里云镜像')
    parser.add_argument('--project-dir', '-p', default='.', help='Gradle项目根目录')
    args = parser.parse_args()

    project_dir = os.path.abspath(args.project_dir)

    if not os.path.isdir(project_dir):
        print(f"错误: 指定的项目目录不存在: {project_dir}")
        return

    print(f"正在配置Gradle项目使用阿里云镜像: {project_dir}")

    # 修改gradle.properties
    modify_gradle_properties(project_dir)

    # 修改build.gradle和build.gradle.kts
    build_gradle_path = os.path.join(project_dir, 'build.gradle')
    build_gradle_kts_path = os.path.join(project_dir, 'build.gradle.kts')

    if os.path.exists(build_gradle_path):
        modify_build_file(build_gradle_path)

    if os.path.exists(build_gradle_kts_path):
        modify_build_file(build_gradle_kts_path)

    # 检查settings.gradle(kts)文件
    settings_gradle_path = os.path.join(project_dir, 'settings.gradle')
    settings_gradle_kts_path = os.path.join(project_dir, 'settings.gradle.kts')

    if os.path.exists(settings_gradle_path):
        modify_build_file(settings_gradle_path)

    if os.path.exists(settings_gradle_kts_path):
        modify_build_file(settings_gradle_kts_path)

    print("配置完成！现在你的Gradle项目将使用阿里云镜像加速依赖下载。")

if __name__ == "__main__":
    main()
